package com.allwinter.yibangsafe.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allwinter.yibangsafe.domain.User;
import com.allwinter.yibangsafe.domain.WxUser;
import com.allwinter.yibangsafe.service.LoginService;
import com.allwinter.yibangsafe.service.UserService;
import com.allwinter.yibangsafe.service.impl.LoginServiceImpl;
import com.allwinter.yibangsafe.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginService loginService;

    /**
     * @param :
     * @return String
     * @author 杨雪松
     * @description 获取所以User表信息
     * @date
     */
    @RequestMapping("/all")
    @ResponseBody
    public String getAllUsers(){
        List<User> users = userService.getUsers();
        String userJson = JSON.toJSONString(users);
        return userJson;
    }

    /**
     * @param user:
     * @return String
     * @author 杨雪松
     * @description 保存user信息
     * @date
     */
    @PostMapping("/save")
    @ResponseBody
    public String saveUser(@RequestBody User user){
        user.setUserid(null);
        System.out.println(user);
        boolean res = userService.saveUser(user);
        if (res){
            return "save sueccess";
        } else {
            return "save false";
        }
    }

    /**
     * @param code:
     * @return String
     * @author 杨雪松
     * @description 用户授权登录，返回openid、session
     * @date
     */
    @GetMapping("/login")
    @ResponseBody
    public String login(String code){
        JSONObject sessionByCode = loginService.getSessionByCode(code);
        String res = sessionByCode.toJSONString();
        return res;
    }

    /**
     * @param data:
     * @return JSONObject
     * @author 杨雪松
     * @description 获取用户信息后，存储wxUser信息
     * @date
     */
    @GetMapping("/saveWxUser")
    @ResponseBody
    public JSONObject saveWxUser(String data){
        System.out.println("WxUserInfo : " + data);
        JSONObject resmsg = loginService.saveWxUserInfo(data);
        return resmsg;
    }

    @PostMapping("/updateUserInfo")
    @ResponseBody
    public JSONObject updateUserInfo(@RequestBody String data) {
        JSONObject res = new JSONObject();
        System.out.println("updateUserInfo: " + data);
        boolean now = userService.updateUser(data);
        if (now) {
            res.put("code",1);
            res.put("msg","update success!");
        } else {
            res.put("code",0);
            res.put("msg","update fail!");
        }
        return res;
    }



    //隐藏接口
    @ResponseBody
    @RequestMapping("/dinjiaxin")
    public String getSunjie(){
        return "丁佳欣是头猪";
    }



}
